package org.petstore.web;


import org.petstore.domain.Account;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;


/**
 * @projectName: MyWebProject
 * @package: org.petstore.web
 * @className: logFilter
 * @author: Eric
 * @description: TODO
 * @date: 2021/11/5 1:45
 * @version: 1.0
 */
public class logFilter implements Filter {
    private PrintWriter writer;
    private String prefix;
    String username;
    HttpSession session;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            // 采用FileWriter 避免每次调用PrintWriter时将txt文件全部清空。
            FileWriter fileWriter = new FileWriter("log.txt", true);
            writer = new PrintWriter(fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
        System.out.println("初始化过滤器");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();

        String IP = request.getRemoteAddr();

        session = request.getSession();
        Account account = (Account) session.getAttribute("loginUser");
        if (account == null)
            username = "localhost";
        else
            username = account.getUsername();
        writer.println(IP + "   " + username + "          " + new Date() + "           " + "         " + requestURI);
        writer.flush();
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("摧毁过滤器");
        if (writer != null)
            writer.close();
    }
}
